package main

import (
	"io"
	"net"
	"os"
	"os/signal"
	"syscall"

	logs "github.com/sirupsen/logrus"
)

func main() {
	os.Remove("/tmp/sock")
	conn, err := net.ResolveUnixAddr("unix", "/tmp/sock")
	if err != nil {
		logs.Error(err)
	}

	listener, err := net.ListenUnix("unix", conn)
	if err != nil {
		logs.Error(err)
	}

	go func() {
		<-HandleSIGINTKILL()

		logs.Info("SIGINTKILL")
		logs.Info("exit main")

		os.Remove("/tmp/sock")

		os.Exit(0)
	}()

	for {
		conn, err := listener.Accept()
		if err != nil {
			logs.Error(err)
		}

		go handleConnection(conn)
	}
}

func handleConnection(conn net.Conn) {
	buf := make([]byte, 1024)
	for {
		n, err := conn.Read(buf)

		if err == io.EOF {
			logs.Info("EOF")
			break
		}

		if err != nil {
			logs.Error(err)
		}

		logs.Info(string(buf[:n]))
	}
}

func HandleSIGINTKILL() chan os.Signal {
	sig := make(chan os.Signal, 1)

	signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)

	return sig
}
